<?php
// +----------------------------------------------------------------------
// | llpt system
// +----------------------------------------------------------------------
// | Copyright (c) 2017 llpt All rights reserved.
// +----------------------------------------------------------------------
// | Author: Gooe <zqscjj@163.com> QQ:81009953
// +----------------------------------------------------------------------
namespace app\admin\controller;
use app\common\controller\Admin;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use think\facade\Cache;
use ddj\Tree;
use ddj\Random;
use think\Facade\Config;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
class Ajax extends Admin
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    /**
     * 清空系统缓存
     */
    public function wipecache()
    {
        $runtime_path = \think\facade\Env::get('runtime_path');
        $wipe_cache_type = [$runtime_path.'cache', $runtime_path.'temp'];
        foreach ($wipe_cache_type as $item)
        {
            $dir = $item;
            if (!is_dir($dir))
                continue;
                $files = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
                    );
    
                foreach ($files as $fileinfo)
                {
                    $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
                    $todo($fileinfo->getRealPath());
                }
    
                //rmdir($dir);
        }
        //Cache::clear();
        $this->success('清除成功');
    }
    /**
     * 读取角色权限树
     */
    public function roletree()
    {
        $model = model('AuthGroup');
        $id = $this->request->post("id");
        $pid = $this->request->post("pid");
        $parentgroupmodel = $model->get($pid);
        if (!$parentgroupmodel){
            $this->error('pid,error~');
        }
        $currentgroupmodel = NULL;
        if ($id)
        {
            $currentgroupmodel = $model->get($id);
        }
        if (($pid || $parentgroupmodel) && (!$id || $currentgroupmodel))
        {
            $id = $id ? $id : NULL;
            //读取父类角色所有节点列表
            $parentrulelist = model('AuthRule')->where(in_array('*', explode(',', $parentgroupmodel->rules)) ? ['status'=>1] : [['status','=',1],['id','in',$parentgroupmodel->rules]] )->select();
            
            //读取当前角色下规则ID集合
            $admin_rule_ids = $this->auth->getRuleIds();
            $superadmin = $this->auth->isSuperAdmin();
            $current_rule_ids = $id ? explode(',', $currentgroupmodel->rules) : [];
    
            if (!$id || !in_array($pid, Tree::instance()->init($model->all(['status' => '1']))->getChildrenIds($id, TRUE)))
            {
                //构造jstree所需的数据
                $nodelist = [];
                foreach ($parentrulelist as $k => $v)
                {
                    if (!$superadmin && !in_array($v['id'], $admin_rule_ids))
                        continue;
                        $state = array('selected' => !$v['ismenu'] && in_array($v['id'], $current_rule_ids));
                        $nodelist[] = array('id' => $v['id'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => $v['title'], 'type' => 'menu', 'state' => $state);
                }
                $this->success('','',$nodelist);
            }
            else
            {
                $this->error('你是爸爸，不能当孙子~');
            }
        }
        else
        {
            $this->error('找不到组织~');
        }
    }
    
    /**
     * 上传文件
     */
    public function upload()
    {
        $this->code = -1;
        $file = $this->request->file('file');
        
        //判断是否已经存在附件
        $sha1 = $file->hash();
        $uploaded = model("attachment")->where('sha1', $sha1)->find();
        if ($uploaded)
        {
            $data = [
                'id' => $uploaded['id'],
                'url' => $uploaded['url'],
                'name' => $uploaded['name']
            ];
            $this->success('上传成功','',$data);
        }
    
        $upload = config('upload.');
    
        preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int) $upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
        $fileInfo = $file->getInfo();
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix ? $suffix : 'file';
        $replaceArr = [
            '{year}'     => date("Y"),
            '{mon}'      => date("m"),
            '{day}'      => date("d"),
            '{hour}'     => date("H"),
            '{min}'      => date("i"),
            '{sec}'      => date("s"),
            '{random}'   => Random::alnum(16),
            '{random32}' => Random::alnum(32),
            '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
            '{suffix}'   => $suffix,
            '{.suffix}'  => $suffix ? '.' . $suffix : '',
            '{filemd5}'  => md5_file($fileInfo['tmp_name']),
        ];
        $savekey = $upload['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
    
        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        //
        $splInfo = $file->validate(['size' => $size,'ext'=>$upload['ext'],'type'=>$upload['mimetype']])->move(\think\facade\Env::get('root_path').'public' . $uploadDir, $fileName);
        if ($splInfo)
        {
            $imagewidth = $imageheight = 0;
            if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']))
            {
                $imgInfo = getimagesize($splInfo->getPathname());
                $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
                $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
            }
            $params = array(
                'name'        => $fileInfo['name'],
                'filesize'    => $fileInfo['size'],
                'imagewidth'  => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype'   => $suffix,
                'imageframes' => 0,
                'mimetype'    => $fileInfo['type'],
                'url'         => $uploadDir . $splInfo->getSaveName(),
                'upload_time' => time(),
                'sha1'        => $sha1
            );
            $attach = model("attachment")->create(array_filter($params));
            
            $data = [
                'id' => $attach->id,
                'url' => $uploadDir . $splInfo->getSaveName(),
                'name' => $attach->name
            ];
            
            //七牛
            $qiniu_cfg = get_db_config(true)['qiniu_cfg'];
            if ($qiniu_cfg['is_open']=='qiniu'){
                self::qiniu($data);
            }
            $this->success('上传成功','',$data);
        }else{
            // 上传失败获取错误信息
            $this->error('上传失败','',$file->getError());
        }
    }
    
    /**
     * 七牛云
     */
    protected function qiniu($data)
    {
        // 需要填写你的 Access Key 和 Secret Key
        $qiniu_cfg = get_db_config(true)['qiniu_cfg'];
        $accessKey = $qiniu_cfg['access_key'];
        $secretKey = $qiniu_cfg['secret_key'];
        $bucket = $qiniu_cfg['bucket'];
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 生成上传 Token
        $token = $auth->uploadToken($bucket);
        // 要上传文件的本地路径
        $filePath = '.'.$data['url'];
        // 上传到七牛后保存的文件名
        $key = basename($filePath);
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        
        if ($err !== null) {
            return false;
        } else {
            return db('attachment')->where('id',$data['id'])->setField('storage','qiniu');
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}